import 'package:dio/dio.dart';
import 'package:life_milestones/controller/MS-global-user-controller.dart';
import 'package:life_milestones/util/MS-config-info-util.dart';
class MSRequest{
  static final MSRequest _instance = MSRequest._();
  MSRequest._();
   static late Dio dio;
   static String _host = "";
   static String lang = "en";
  factory MSRequest(){

    return _instance;
  }

  set host(String value){
    _host = value;
  }

  Map<String,String> getHeader(){
    var headers = <String,String>{};
    headers['device-id'] = MSConfigInfoUtil().deviceId;
    headers["platform"]  = "iOS";
    headers['model'] = MSConfigInfoUtil().model;
    headers['pkg']   = MSConfigInfoUtil().package;
    headers['ver']   = MSConfigInfoUtil().version;
    headers['p_ver'] = MSConfigInfoUtil().buildNumber;
    headers['kst']   = '1';
    headers["content-type"] = "application/json";

    return headers;
  }

  init()async{
     dio = Dio(BaseOptions(
         baseUrl: _host,
         headers: getHeader()
     ));
     dio.interceptors.add(MSInterceptor());
  }

  Future<T?> post<T>(String path,{Object? data,Map<String,dynamic>? queryParameters})async{
    try{
      dio.options.headers["content-type"] = "application/json";
      var response = await dio.post<T>(path,data: data,queryParameters: queryParameters);
      print(response);
      return response.data;
    }catch(e){
      return null;
    }

  }

  Future<T?> get<T>(String path,{Map<String,dynamic>? queryParameters})async{
    var response = await dio.get<T>(path,queryParameters: queryParameters,);
    print(response);
    return response.data;
  }

  Future<T?> postForm<T>(String path,{Map<String,dynamic>? data})async{
    dio.options.headers["content-type"] = "application/x-www-form-urlencoded";
    var response = await dio.post<T>(path,queryParameters: data);
    return response.data;
  }

  Future<T?> uploadFile<T>(String path,{FormData? data,Map<String,dynamic>? header})async{
    var response = await dio.post<T>(path,data: data);
    return response.data;
  }
}


class MSInterceptor extends Interceptor{
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    options.headers['sys_lan'] = MSGlobalUserController().lang;
    options.headers['lang'] = MSGlobalUserController().lang;
    if(MSGlobalUserController().token != null){
      options.headers['Authorization'] = "Bearer${MSGlobalUserController().token}";
    }
    handler.next(options);
  }
}